import wepy from 'wepy';

export default class Home extends wepy.mixin {
  data = {
    // 搜索框里的双向绑定的值
    value: '',
    // 根据搜索框的值获取的的数据
    suggestList: [],
    // 搜索框的搜索记录
    history: wepy.getStorageSync('history') || [],
    timer: null,
  };

  config = {};

  methods = {
    // 搜索框的value值发生改变时触发
    onChange(e) {
      clearTimeout(this.timer);
      this.value = e.detail.trim();
      if (this.value.length === 0) return (this.suggestList = []);
      // 获取搜索列表
      clearTimeout(this.timer);
      this.timer = setTimeout(async () => {
        const { data: res } = await wepy.get('/goods/qsearch', {
          query: this.value
        });
        if (res.meta.status !== 200) return wepy.baseToast();
        this.suggestList = res.message;
        this.$apply();
      }, 500);
    },

    // 搜索框回车时触发 并将搜索记录保存起来
    onSearch() {
      clearTimeout(this.timer);
      if (this.value.length === 0) return;

      if (this.history.indexOf(this.value) === -1) {
        setTimeout(() => {
          this.history.unshift(this.value);
        }, 500);
        this.history = this.history.slice(0, 10);
        wepy.setStorageSync('history', this.history);
      }

      wepy.navigateTo({
        url: '/pages/goods_list?query=' + this.value,
        query: this.value
      });
    },
    // 点击删除搜索历史
    removeHistory() {
      this.history = [];
      wepy.setStorageSync('history', []);
    },
    // 点击搜索历史标签跳转值商品列表
    togoodslist(item){
      const i=item.currentTarget.dataset.item
      wepy.navigateTo({
        url: `/pages/goods_list?query=${i}`,
      });
      
    }
  };
  onHide() {
    setTimeout(() => {
      this.value = '';
      this.suggestList = [];
    }, 500);
  }
  onShow(){
    this.$parent.setTabBarBadge()
  }
}
